/**
 * Author: Bob Chen
 */

package net.uman.framework.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.uman.entity.Resource;
import net.uman.entity.User;
import net.uman.framework.modules.security.springsecurity.SpringSecurityUtils;
import net.uman.service.ResourceManager;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
/**
 * 附件上传
 * @author lihengjun_dt
 *
 */
public class ResourceUploadServlet extends HttpServlet {  
	private static final long serialVersionUID = 5494491470319306849L;
	
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
    	
    	String target = request.getParameter("target");
    	
    	if (target==null ) {
			System.err.println("exit because of target ========== "+target);
			return;
		}
    	
    	response.setContentType("text/plain");
    	
    	if ("resource".equals(target)) {		//上传资源
    		uploadResource(request, response);
		}else {									//上传头像
			
		}
    }
    
    @SuppressWarnings("unused")
	private String uploadResource(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String description = request.getParameter("description");		//描述
        String keyWord = request.getParameter("keyWord");				//关键词
        String needPointString = request.getParameter("needPoint");		//下载积分
        String name = request.getParameter("name");		//下载积分
        Integer needPoint = Integer.parseInt(needPointString);
        
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        User user = SpringSecurityUtils.getCurrentUser();				//当前用户
        StoreOrderType sot = new StoreOrderType();
        List<JSONObject> jsonObjectResults = new ArrayList<JSONObject>();
        
        try {
        	
            String today = new SimpleDateFormat("yyMMdd").format(new Date());
            List items = upload.parseRequest(request);
            Iterator it = items.iterator();
            List<Resource> resources = new ArrayList<Resource>();
            while (it.hasNext()) {
            	FileItem item = (FileItem) it.next();
            	Resource resource = new Resource();
                String url = sot.StoreFile("files", item, today);
                
                resource.setAddDate(new Date());
                resource.setAddUserId(user.getId());
                resource.setAddUserName(user.getName());
                resource.setDescription(description);
                resource.setKeyWord(keyWord);
                resource.setName(name);
                resource.setNeedPoint(needPoint);
                resource.setUrl(url);
                
                JSONObject jsonObject = new JSONObject();
                jsonObjectResults.add(jsonObject);
                if (item.getSize()>50*1024*1024) {
					jsonObject.put("over_file_size_limit", true);
					jsonObject.put("message", "当前附件大小为:"+item.getSize()/(1024*1024)+"M,超出上传附件大小限制!!!");
					continue;
				}else {
					jsonObject.put("over_file_size_limit", false);
					jsonObject.put("message", "添加成功!!!!");
				}
                resources.add(resource);
            }
            
            if (resources!=null&&!resources.isEmpty()&&resources.size()>0) {
            	ResourceManager resourceManager = getResourceManagerInstance(request);
            	for (Resource resource : resources) {
            		if (resource!=null) {
            			resourceManager.addResource(resource);//添加到数据库
            		}
				}
			}
            
            response.getWriter().print(jsonObjectResults.get(0));
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	/**
	 *
	 * 功能描述：获取orderManagerFacade实例
	 *
	 * @param request
	 * @return
	 */
	private ResourceManager getResourceManagerInstance(
			HttpServletRequest request) {
		ApplicationContext context = (ApplicationContext)request.getSession().getServletContext()
       	.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 
       return (ResourceManager)context
       	.getBean(ResourceManager.SPRING_BEAN_NAME, ResourceManager.class);
	}
}
